package com.stormragetech.arthas.process.invocation;

import com.stormragetech.arthas.codec.ArthasHttpRequestDecodeHandler;
import com.stormragetech.arthas.common.constant.Constant;
import com.stormragetech.arthas.common.exception.ArthasException;
import com.stormragetech.arthas.common.util.Assert;
import com.stormragetech.arthas.process.proxy.Proxy;
import com.stormragetech.arthas.serialize.ArthasHttpRequestSerializeHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * description: action invoker implements interface
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
public class ActionInvoke implements Invoke {

    private Proxy proxy;

    public ActionInvoke(Proxy proxy) {
        Assert.notNull(proxy, "FactoryProxy cannot be null !!!");
        this.proxy = proxy;
        proxy.setInvoke(this);
    }

    @Override
    public String invoke() throws ArthasException {

        try {
            Method method = proxy.getMethod();
            Object[] target = new ArthasHttpRequestSerializeHandler(method, new ArthasHttpRequestDecodeHandler(method).process()).handle();
            return (String) proxy.getMethod().invoke(proxy.getAction(), target);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ArthasException(Constant.PROC_ERR_CODE, Constant.PROC_ERR_INVOK, ArthasException.APP_ERR);
        }
    }
}
